<?php

/**
 * Retrieve Post Ids and date.
 *
 * @since 2.2.0
 *
 * @param array $args Method parameters.
 * @return array
 */
function mektoub_getPostIds($args) {
	global $wpdb;

	$username	= $wpdb->escape($args[0]);
	$password	= $wpdb->escape($args[1]);
	if (isset($args[2])) {
		$year	= (int) $wpdb->escape($args[2]);
	} else {
		$year	= 2009; 
	}
	if (isset($args[3])) {
		$month	= (int) $wpdb->escape($args[3]);
	} else {
		$month	= 1; 
	}

	logIO('I', "Checking if XML-RPC is enable");
	if ( !get_option( 'enable_xmlrpc' ) ) {
		return new IXR_Error( 405, __( 'XML-RPC services are disabled on this blog') );
	}

	logIO('I', "Checking user/password");
	if (!user_pass_ok($username, $password)) {
		return new IXR_Error(403, __('Bad login/pass combination.'));
	}

	logIO('I', "Checking user permissions");
	set_current_user( 0, $username );
	if( !current_user_can( 'edit_pages' ) ) {
		return new IXR_Error( 401, __( 'Sorry, you can not edit posts.' ) );
	}

	//do_action('xmlrpc_call', 'mektoub_getPostIds');

	if (!function_exists('get_posts')) {
		return new IXR_Error( 500, __( 'Sorry, some internal functions are not available.' ) );
	}

	logIO('I', "Getting Posts");
	/*$sql_query = "SELECT ID, post_date FROM $wpdb->posts";
	$sql_query .= " WHERE YEAR($wpdb->posts.post_date) = $year AND MONTH($wpdb->posts.post_date) = $month";
	$sql_query .= " ORDERBY ";
	$wpdb->get_results($sql_query);*/
	$posts = get_posts( "year=$year&monthnum=$month&post_type=post&post_status=publish&orderby=date&order=ASC&numberposts=-1" );//&numberposts=0 //{$page_limit}" );
	logIO('I', "Counting Posts");
	$num_posts = count($posts);

	// If we have posts, put together their info.
	if($num_posts >= 1) {
		logIO('I', "Found posts. Constructing response");
		$posts_struct = array();
		for($i = 0; $i < $num_posts; $i++) {
			logIO('I', "Handling Post ID: ".$posts[$i]->ID);
			$post_data = wp_get_single_post($posts[$i]->ID, ARRAY_A);
			$posts_struct[] = array(
			   'postid' => $post_data['ID'],
			   'dateCreated' => new IXR_Date(mysql2date('Ymd\TH:i:s', $post_data['post_date']))
			);
		}
		logIO('O', "Returning response: ".$posts_struct);
		return($posts_struct);
	} 
	// If no posts were found return an error.
	else {
		logIO('O', "No posts. Returning empty array");
		return(array());
	}
}

function add_custom_xmlrpc_methods($methods) {
	$methods['mektoub.getPostIds'] = 'mektoub_getPostIds';
	return $methods;
}

add_filter('xmlrpc_methods', 'add_custom_xmlrpc_methods');

?>
